/* eslint-env node */
import { app, BrowserWindow, globalShortcut, shell } from 'electron';

const isMac = process.platform === 'darwin';
let canBlur = true;
export default function whenReady(win = new BrowserWindow()) {
  const hideWin = async () => {
    if (!canBlur) {
      return;
    }
    if (!isMac) {
      win.minimize();
      win.hide();
    } else {
      app.hide();
    }
    // 取消监听ESC
    globalShortcut.unregister('Escape');
  };

  const showWin = async () => {
    if (isMac) {
      win.setVisibleOnAllWorkspaces(true);
      canBlur = false;
      await new Promise((r) => setTimeout(r));
      win.setVisibleOnAllWorkspaces(false);
      await new Promise((r) => setTimeout(r, 100));
      canBlur = true;
    }
    win.show();

    // 监听 esc按下， 关闭窗口
    globalShortcut.register('Escape', hideWin);
  };

  showWin();

  // 失去焦点时隐藏窗口
  win.on('blur', hideWin);

  // 注册全局快捷键
  const macKey = 'CommandOrControl+Shift+D';
  const winKey = 'Shift+Alt+D';
  const key = isMac ? macKey : winKey;
  globalShortcut.register(key, showWin);

  win.webContents.on('before-input-event', (event, input) => {
    // macOS: Cmd+W | Windows/Linux: Ctrl+W
    if ((input.key.toLowerCase() === 'w' && input.meta) || (input.key.toLowerCase() === 'w' && input.ctrl)) {
      hideWin();
      event.preventDefault(); // 阻止默认关闭行为
    }
    // Cmd+Q
    if (input.key.toLowerCase() === 'q' && input.meta) {
      hideWin();
      event.preventDefault(); // 阻止默认关闭行为
    }
  });
  win.webContents.on('will-navigate', (event, url) => {
    // 允许刷新
    if (url === win.webContents.getURL()) {
      return;
    }
    // 拦截所有导航请求
    event.preventDefault();

    // 使用默认浏览器打开
    shell.openExternal(url);
  });
  win.webContents.setWindowOpenHandler(({ url }) => {
    // 允许刷新
    if (url === win.webContents.getURL()) {
      return;
    }
    // 使用默认浏览器打开
    shell.openExternal(url);
    return { action: 'deny' }; // 阻止Electron创建新窗口
  });
}

// 退出时注销所有快捷键
app.on('will-quit', () => {
  globalShortcut.unregisterAll();
});
